//
//  FloatingView.m
//  FuncFanc
//
//  Created by careate-hubing on 2021/7/2.
//  Copyright © 2021 huhu. All rights reserved.
//

#import "FloatingView.h"
#import "MusicPlayViewController.h"

@interface FloatingView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *musicTableview;
@property (nonatomic,strong) UIPanGestureRecognizer *pan;
@end

@implementation FloatingView

+(instancetype)sharedView
{
    static FloatingView *_sharedFloatView = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedFloatView = [[super allocWithZone:NULL]init];
    });
    return _sharedFloatView;
}

// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [FloatingView sharedView];
}

// 防止外部调用copy
- (id)copyWithZone:(nullable NSZone *)zone {
    return [FloatingView sharedView];
}

// 防止外部调用mutableCopy
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
    return [FloatingView sharedView];
}

-(instancetype)init{
    if (self = [super init]) {
        [self createSubviews];
        _musicList = [NSMutableArray array];//[MusicModel musicLibrary];
        _currentIndex = 0;
    }
    return self;
}

-(void)createSubviews
{
    self.backgroundColor = NAVI_BAR_SKYBLUE;
    self.layer.cornerRadius = 60/2;
    self.layer.masksToBounds = YES;
    self.layer.borderColor = NAVI_BAR_SKYBLUE.CGColor;
    self.layer.borderWidth = 2.0;
    
    _openBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_openBtn setTitle:@"打开" forState:UIControlStateNormal];
    [_openBtn setTitle:@"折叠" forState:UIControlStateSelected];
    _openBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_openBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _openBtn.layer.cornerRadius = 60/2;
    _openBtn.layer.masksToBounds = YES;
    _openBtn.backgroundColor = NAVI_BAR_SKYBLUE;
    [self addSubview:_openBtn];
    [_openBtn addTarget:self action:@selector(openBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playBtn setTitle:@"播放" forState:UIControlStateNormal];
    [_playBtn setTitle:@"暂停" forState:UIControlStateSelected];
    [_playBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [_playBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
//    [_playBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateSelected];
    [self addSubview:_playBtn];
    [_playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _songName = [[UILabel alloc]init];
    _songName.textColor = [UIColor whiteColor];
    _songName.numberOfLines = 0;
    _songName.font = [UIFont systemFontOfSize:14];
    [self addSubview:_songName];
    
    _singer = [[UILabel alloc]init];
    _singer.textColor = [UIColor whiteColor];
    _singer.font = [UIFont systemFontOfSize:12];
    [self addSubview:_singer];
    
    _playOrder = [UIButton buttonWithType:UIButtonTypeCustom];
    _playOrder.titleLabel.font = [UIFont systemFontOfSize:12];
    [_playOrder setTitle:@"显示音乐列表" forState:UIControlStateNormal];
    [_playOrder setTitle:@"隐藏音乐列表" forState:UIControlStateSelected];
    [_playOrder setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_playOrder addTarget:self action:@selector(musicListBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_playOrder];
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextBtn setTitle:@"下一首" forState:UIControlStateNormal];
    [_nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:_nextBtn];
    
    _lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_lastBtn setTitle:@"上一首" forState:UIControlStateNormal];
    [_lastBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:_lastBtn];

    _pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panFloatView:)];
    [self addGestureRecognizer:_pan];
}

-(void)musicListBtnClick:(UIButton *)aBtn
{
    if (_musicList.count == 0) {
        MusicPlayViewController *player = [[MusicPlayViewController alloc]init];
        player.hidesBottomBarWhenPushed = YES;
        [[AppDelegate sharedAppDelegate]pushViewController:player animated:YES];
        return;
    }
    _playOrder.selected = !_playOrder.selected;
    if (_playOrder.selected)
    {
        // 显示
        [self showMusicList];
    }
    else
    {
        // 隐藏
        [self hideMusicList];
    }
}

-(void)addMusicModelToPlayListWith:(NSArray <MusicModel *>*)aMusicList
{
    BOOL isContain = NO;
    for (MusicModel *newMusic in aMusicList) {
        for (MusicModel *music in _musicList) {
            if ([music.musicPath isEqualToString:newMusic.musicPath]) {
                isContain = YES;
                continue;
            }
        }
        if (!isContain) {
            [_musicList addObject:newMusic];
        }
    }
    [self startMusicPlayWith:aMusicList.firstObject];
}

-(void)openBtnClick:(UIButton *)aBtn
{
    aBtn.selected = !aBtn.selected;
    if (!aBtn.selected) {
        [self foldPlayView];
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
    }
    else
    {
        [self openPlayView];
        //开始计时。view 被点击时，重置时间，不被点击10秒后，折叠foldPlayView。
//        __weak typeof(self) ws = self;
        _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            [ws openBtnClick:self->_openBtn];
        }];
    }
}

-(void)playBtnClick:(UIButton *)aBtn
{
    aBtn.selected = !aBtn.selected;
    if (!aBtn.selected) {
        if (_currentIndex >= _musicList.count) {
            _currentIndex = 0;
        }
        MusicModel *model = _musicList[_currentIndex];
        [self startMusicPlayWith:model];
    }
    else
    {
        [self stopMusic];
    }
}

-(void)startMusicPlayWith:(MusicModel *)musicModel
{
    if (_audioPlayer.playing) {
        [_audioPlayer stop];
        return;
    }
    NSError *error = nil;
    //初始化播放器
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:[musicModel.musicPath stringByUrlEncoding]] error:&error];
    
    _songName.text = [NSString stringWithFormat:@"%@",musicModel.musicName];
    
    //是否循环播放
    _audioPlayer.numberOfLoops = 0;

    //把播放文件加载到缓存中（注意：即使在播放之前音频文件没有加载到缓冲区程序也会隐式调用此方法。）
    [_audioPlayer prepareToPlay];

    //设置代理，监听播放状态(例如:播放完成)
    _audioPlayer.delegate = self;

    // 设置音频会话模式，后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    // 添加通知(输出改变通知)  ios 6.0 后
    if (error) {
        DebugLog(@"%@",error.description);
    }
    [_audioPlayer play];
}

// 当前歌曲播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    _currentIndex ++;
    if (_currentIndex >= _musicList.count) {
        _currentIndex = 0;
    }
    MusicModel *nextMusic = _musicList[_currentIndex];
    [self startMusicPlayWith:nextMusic];
}

-(void)stopMusic
{
    [_audioPlayer stop];
}

-(void)layoutSubviews
{
    [_openBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.bottom.equalTo(self);
        make.width.height.mas_equalTo(60);
    }];
}

-(void)foldPlayView
{
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ScreenWidth-80);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    [self openOrFoldView:YES];
    
    // 折叠的时候，添加收拾。
    [self addGestureRecognizer:_pan];
}

-(void)openOrFoldView:(BOOL)isHidden
{
    _playBtn.hidden = isHidden;
    _playOrder.hidden = isHidden;
    _songName.hidden = isHidden;
    _singer.hidden = isHidden;
    _nextBtn.hidden = isHidden;
    _lastBtn.hidden = isHidden;
    self.musicTableview.hidden = isHidden;
}

-(void)showMusicList
{
    [self openPlayView];
    // 打开的时候，移除手势。
    [self removeGestureRecognizer:_pan];
    
    CGFloat tableH = _musicList.count *40;
    CGFloat selfH = tableH + 60;
    if (selfH >= SCREEN_HEIGHT/3*2) {
        selfH = SCREEN_HEIGHT/3*2;
    }

    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(selfH);
    }];
    
    [self.musicTableview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.left.equalTo(self);
        make.right.equalTo(self);
        make.bottom.equalTo(_playBtn.mas_top).offset(0);
    }];
}

-(void)hideMusicList
{
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(60);
    }];
    [self.musicTableview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(0);
        make.bottom.equalTo(_playBtn.mas_top).offset(0);
        make.left.equalTo(self);
    }];
}

-(void)openPlayView
{
    [self openOrFoldView:NO];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(ScreenWidth - 40);
    }];

    [_playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(2);
        make.height.width.mas_equalTo(60);
        make.bottom.equalTo(self);
    }];
    
    [_playOrder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_openBtn.mas_left).offset(5);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(60);
        make.bottom.equalTo(self);
    }];
    [_songName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_playBtn.mas_right).offset(5);
        make.right.equalTo(_playOrder.mas_left).offset(-5);
        make.bottom.equalTo(self);
        make.height.mas_equalTo(60);
    }];
    [_singer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_playBtn.mas_right).offset(5);
        make.right.equalTo(_playOrder.mas_left).offset(-5);
        make.bottom.mas_equalTo(-5);
        make.height.mas_equalTo(25);
    }];
}

-(void)panFloatView:(UIPanGestureRecognizer *)pan
{
    CGPoint panPoint;
    panPoint = [pan locationInView:[UIApplication sharedApplication].keyWindow];
    if(pan.state == UIGestureRecognizerStateBegan)
    {
        
    }
    else if(pan.state == UIGestureRecognizerStateChanged)
    {
        self.center = CGPointMake(panPoint.x, panPoint.y);
    }
    else if(pan.state == UIGestureRecognizerStateEnded)
    {
        if(panPoint.x <= Main_Screen_Width/2)
        {
            if (panPoint.y <= (IS_iPhoneX?88:64)+44)
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(81/2, (IS_iPhoneX?88:64)+44+144/2);
                }];
            }
            else if (panPoint.y >= Main_Screen_Height-144)
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(81/2, Main_Screen_Height-(IS_iPhoneX?34:0)-144/2);
                }];
            }
            else
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(81/2, panPoint.y);
                }];
            }
        }
        else if(panPoint.x > Main_Screen_Width/2)
        {
            if (panPoint.y <= (IS_iPhoneX?88:64)+44)
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(Main_Screen_Width - 81/2, (IS_iPhoneX?88:64)+44+144/2);
                }];
            }
            else if (panPoint.y >= Main_Screen_Height-144)
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(Main_Screen_Width - 81/2, Main_Screen_Height-(IS_iPhoneX?34:0)-144/2);
                }];
            }
            else
            {
                [UIView animateWithDuration:0.25 animations:^{
                    self.center = CGPointMake(Main_Screen_Width - 81/2, panPoint.y);
                }];
            }
        }
    }
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _musicList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    MusicModel *music = _musicList[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",music.musicName];
    cell.backgroundColor = NAVI_BAR_SKYBLUE;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicModel *music = _musicList[indexPath.row];
    [self startMusicPlayWith:music];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_musicList removeObjectAtIndex:indexPath.row];
    [self.musicTableview beginUpdates];
    [self.musicTableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.musicTableview endUpdates];
}

#pragma mark -懒加载
-(UITableView *)musicTableview
{
    if (!_musicTableview) {
        _musicTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _musicTableview.separatorColor = [UIColor redColor];
        _musicTableview.backgroundColor = NAVI_BAR_SKYBLUE;
        _musicTableview.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _musicTableview.delegate = self;
        _musicTableview.dataSource = self;
        [self addSubview:_musicTableview];
    }
    return _musicTableview;
}





@end
